import { RbacMenuType } from '@/data/auth/menu';
import { tablePage } from '@/services/data';
import { handleAdd, handleRemove, handleRemoveList, handleUpdate } from '@/services/handle';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable,
} from '@ant-design/pro-components';

import { PageParams } from '@/data/result';
import { CorrelationTypeEnum } from '@/enums/auth';
import { IconOutlinedValueEnum } from '@/enums/icon';
import { useMenus } from '@/hooks/auth/useMenus';
import AddModal from '@/pages/auth/rbacMenu/components/AddModal';
import AddPermModal from '@/pages/auth/rbacMenu/components/AddPermModal';
import AddButtom from '@/pages/auth/rbacMenu/components/button/AddButtomTableModal';
import UpdateModal from '@/pages/auth/rbacMenu/components/UpdateModal';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Drawer } from 'antd';
import React, { useRef, useState } from 'react';

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<RbacMenuType>();
  const [selectedRowsState, setSelectedRows] = useState<RbacMenuType[]>([]);

  const [addPermModalVisible, handleAddPermModalVisible] = useState<boolean>(false);
  const [addButtonModalVisible, handleAddButtonModalVisible] = useState<boolean>(false);

  const { allMenuValueEnum } = useMenus();

  // @ts-ignore
  const columns: ProColumns<RbacMenuType>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '图标',
      dataIndex: 'icon',
      hideInSearch: true,
      render: (dom, { icon, parentId }) => {
        if (parentId) {
          return null;
        }
        if (typeof icon === 'string' && IconOutlinedValueEnum[icon]) {
          return IconOutlinedValueEnum[icon];
        }
        return null;
      },
    },
    {
      title: '菜单中文名称',
      dataIndex: 'cnName',
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
    },
    {
      title: '路由路径',
      dataIndex: 'path',
    },

    {
      title: '父级ID',
      dataIndex: 'parentId',
      valueEnum: allMenuValueEnum,
    },

    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch: true,
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        // 基础操作数组
        const actions = [
          <a
            key="update"
            onClick={() => {
              handleUpdateModalVisible(true);
              setCurrentRow(record);
              setShowDetail(false);
            }}
          >
            更新
          </a>,
          <a
            key="auth"
            onClick={() => {
              handleAddPermModalVisible(true);
              setCurrentRow(record);
              setShowDetail(false);
            }}
          >
            授权
          </a>,
          <a
            key="remove"
            onClick={async () => {
              await handleRemove('/system/rbacMenu', record.id);
              if (actionRef.current) {
                await actionRef.current.reload();
              }
              setShowDetail(false);
            }}
          >
            删除
          </a>,
        ];

        if (record.parentId) {
          actions.splice(
            2,
            0,
            <a
              key="button"
              onClick={() => {
                handleAddButtonModalVisible(true);
                setCurrentRow(record);
                setShowDetail(false);
              }}
            >
              增加按钮
            </a>,
          );
        }

        return actions;
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<RbacMenuType, PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => {
          return tablePage('/system/rbacMenu', params);
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveList('/system/rbacMenu', selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <UpdateModal
        onSubmit={async (values: any) => {
          const success = await handleUpdate('/system/rbacMenu', values, currentRow);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <AddModal
        onSubmit={async (value) => {
          const success = await handleAdd('/system/rbacMenu', value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        visible={createModalVisible}
      />
      <AddButtom
        onCancel={() => handleAddButtonModalVisible(false)}
        visible={addButtonModalVisible}
        values={currentRow || {}}
      />
      <AddPermModal
        onSubmit={async (value) => {
          const permissionIds = value?.targetKeys;
          const menuOrBtnId = currentRow?.id;
          const success = await handleAdd('/system/rbacPermissionMenuBtn', {
            permissionIds,
            menuOrBtnId,
            correlationType: 1,
          });

          if (success) {
            handleAddPermModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              await actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleAddPermModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={addPermModalVisible}
        values={currentRow || {}}
        correlationType={CorrelationTypeEnum.MENU}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<RbacMenuType>
            column={1}
            title={currentRow?.id}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<RbacMenuType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
